package com.example.juyixia;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.google.common.collect.Maps;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.location.SettingInjectorService;
import android.media.audiofx.BassBoost.Settings;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.util.Log;
import android.widget.Toast;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class LoginActivity extends Activity implements OnClickListener{
	 private Myinfo myinfo;
	private Button mBtn_login;
	private EditText mEt_username;
	private EditText mEt_password;
	private TextView tips;
	private String str;
	private String ipstr;
	private Button btn_qtlogin;
	private final String DEBUG_TAG = "Activity01";
	public static final String bm="utf-8";
	private static final String TAG="TestTag";
	/** 
	   * 定义加密方式 
	   */
	  private final static String KEY_RSA = "RSA"; 
	  static Map<String, Object> keymap;
	  /** 
	   * 定义签名算法 
	   */
	  private final static String KEY_RSA_SIGNATURE = "MD5withRSA"; 
	  /** 
	   * 定义公钥算法 
	   */
	  private final static String KEY_RSA_PUBLICKEY = "RSAPublicKey"; 
	  /** 
	   * 定义私钥算法 
	   */
	  private final static String KEY_RSA_PRIVATEKEY = "RSAPrivateKey";
	  /** 
	   * 初始化密钥 
	   * @return 
	   */
	  public static Map<String, Object> init() { 
	     keymap = Maps.newHashMap();  
	    try { 
	      KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_RSA); 
	      generator.initialize(1024); 
	      KeyPair keyPair = generator.generateKeyPair(); 
	      // 公钥 
	      RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); 
	      // 私钥 
	      RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); 
	      // 将密钥封装为map 
	      keymap.put(KEY_RSA_PUBLICKEY, publicKey); 
	      keymap.put(KEY_RSA_PRIVATEKEY, privateKey); 
	    } catch (NoSuchAlgorithmException e) { 
	      e.printStackTrace(); 
	    } 
	    return keymap; 
	  } 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		keymap=init();
		myinfo=(Myinfo) getApplication();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		mBtn_login = (Button) findViewById(R.id.btn_login);
		mEt_username = (EditText) findViewById(R.id.username);
		mEt_password = (EditText) findViewById(R.id.userpwd);
		btn_qtlogin = (Button) findViewById(R.id.btn_qtlogin);
		btn_qtlogin.setOnClickListener(this);
		tips = (TextView) findViewById(R.id.tips);
		// initViews();
		mBtn_login.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
             tips.setText("用户名或密码错误！");
				new Thread() {
					public void run() {				
						Socket socket = null;
						//String message = mEt_username.getText().toString() + "," + mEt_password.getText().toString();
						try {
							// 创建Socket
							// socket = new Socket("192.168.1.110",54321);

							socket = new Socket("172.16.96.43", 45321); // IP一定是本地机器的ip
                            String publickey=getPublicKey(keymap);
                            String privatekey=getPrivateKey(keymap);
							//message = message + "," + socket.getLocalAddress()+","+publickey+","+privatekey;
							// 向服务器发送消息
                            Map<String, String> loginmap=new HashMap<String, String>();
                            loginmap.put("用户名", mEt_username.getText().toString());
                            loginmap.put("密码", mEt_password.getText().toString());
                            loginmap.put("ip", socket.getLocalAddress().toString());
                            loginmap.put("公钥", publickey);
                            loginmap.put("私钥", privatekey);
                            JSONObject json=new JSONObject(loginmap);
                            PrintWriter out = new PrintWriter(
									new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),bm)), true);
							out.println(json.toString());
							BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),bm));
							String msg = br.readLine();
                         
							if (!msg.equals("0")) {
								/*
								 * 将从服务器返回的用户信息与用户好友信息存入Myinfo全局对象
								 */
								JSONObject userjson=new JSONObject(msg);
								JSONArray friends=userjson.getJSONArray("friends");
								JSONObject userown=userjson.getJSONObject("user");
								JSONTokener userParser = new JSONTokener(userown.toString());        
							    JSONObject person = (JSONObject) userParser.nextValue();    
							    // 接下来的就是JSON对象的操作了    
                                List<Myinfo> myfriend=new ArrayList<Myinfo>();
                                for(int i=0;i<friends.length();i++){
                                	Myinfo friendinfo=new Myinfo();
                                	JSONObject friendjson=friends.getJSONObject(i);
                                	JSONTokener friendParser = new JSONTokener(friendjson.toString());        
    							    JSONObject friend = (JSONObject) friendParser.nextValue();  
    							    friendinfo.setUserid(friend.getString("userid"));
    							    friendinfo.setUsername(friend.getString("username"));
    							    friendinfo.setSex(friend.getString("sex"));
    							    friendinfo.setUserpwd(friend.getString("userpwd"));
    							    friendinfo.setUserage(friend.getString("userage"));
    							    friendinfo.setUserip(friend.getString("userip"));
                                	myfriend.add(friendinfo);
                                }
                                myinfo.setUserip(person.getString("userip"));
								myinfo.setUserid(person.getString("userid"));
								myinfo.setUsername(person.getString("username"));
								myinfo.setSex(person.getString("sex"));
								myinfo.setUserpwd(person.getString("userpwd"));
								myinfo.setUserage(person.getString("userage"));
								myinfo.setUserfriend(myfriend);
								Intent intent = new Intent(LoginActivity.this, MainActivity.class);
								startActivity(intent);
								tips.setText("");
							}
							
							
							br.close();
							out.close();

							// 关闭Socket
							socket.close();
						} catch (Exception e) {
							// TODO: handle exception
							Log.e(DEBUG_TAG, e.toString());
						}

						handler.sendEmptyMessage(0);// 执行完毕后给handler发送一个空消息
					}

					// 定义Handler对象
					private Handler handler = new Handler() {
						@Override
						// 当有消息发送出来的时候就执行Handler的这个方法
						public void handleMessage(Message msg) {
							super.handleMessage(msg);
							// 处理UI
							System.out.println("OK?");
						}
					};
				}.start();// 启动一个线程
              
			}
			
		}); 
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_qtlogin:
			Intent intent = new Intent(this, SignUpActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
	}
	 public static String getPublicKey(Map<String, Object> map) { 
		    String str = ""; 
		    try { 
		      Key key = (Key) map.get(KEY_RSA_PUBLICKEY); 
		      str = encryptBase64(key.getEncoded()); 
		    } catch (Exception e) { 
		      e.printStackTrace(); 
		    } 
		    return str; 
		  } 
		  
		  /** 
		   * 获取私钥 
		   * @param map 
		   * @return 
		   */
		  public static String getPrivateKey(Map<String, Object> map) { 
		    String str = ""; 
		    try { 
		      Key key = (Key) map.get(KEY_RSA_PRIVATEKEY); 
		      str = encryptBase64(key.getEncoded()); 
		    } catch (Exception e) { 
		      e.printStackTrace(); 
		    } 
		    return str; 
		  } 
		  /** 
		   * BASE64 解密 
		   * @param key 需要解密的字符串 
		   * @return 字节数组 
		   * @throws Exception 
		   */
		  public static byte[] decryptBase64(String key) throws Exception { 
		    return (new BASE64Decoder()).decodeBuffer(key); 
		  } 
		  
		  /** 
		   * BASE64 加密 
		   * @param key 需要加密的字节数组 
		   * @return 字符串 
		   * @throws Exception 
		   */
		  public static String encryptBase64(byte[] key) throws Exception { 
		    return (new BASE64Encoder()).encodeBuffer(key); 
		  } 
}


